<?php

class UrlClassController extends Controller
{
	
	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','ajaxgetlist','search','multipleupdate'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		echo 'greate';
		exit;
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$this->layout = 'main';
		
		$model=new UrlClass;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		if(isset($_POST['UrlClass']))
		{
			$UrlClassInfo = array();
			$UrlClassInfo = $_POST['UrlClass'];
			$parentid_arr = $_POST['parentid'];
			$parent_id = 0;
			while(true){
				$tmp_parent_id = array_pop($parentid_arr);
				if($tmp_parent_id > 0 ){
					$parent_id = $tmp_parent_id;
					break;
				} 
			}
						
			$model->attributes=$_POST['UrlClass'];
			$model-> parentid = $parent_id;
			if($model->save()){
				//$model->updateClassPath();
				showmsg('添加成功！',Yii::app()->createUrl('UrlClass/index'));
			}
		}
		//获取根分类
		//$root_class = $model->getSubClass();
		//$jsFile = Yii::app()->theme->baseUrl.'/assets/js/common.js';
		//Yii::app()->clientScript->registerScriptFile($jsFile);
		$parentClassHtml = '';
		$classArr = array();
		$classArr = $model->getSubClass(0);
		$classArr = array(0=>'全部')+$classArr;
		$parentClassHtml .= CHtml::dropDownList('parentid[]',0, $classArr,array('id'=>'parentid_0','onchange'=>'selectClass(this)'));
		
		$root_class = array();
		$this->render('create',array(
			'model'=>$model,
			'parentClassHtml'=>$parentClassHtml,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate()
	{
		$m = new UrlClass();
		//echo CHtml::dropDownList('aa', 0, array(0=>'请选择',1=>'专业'));
		$this->layout = 'main';
		
		if(isset($_GET['id'])){
			$id = intval($_GET['id']);
		}
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		if(isset($_POST['UrlClass']))
		{
			$UrlClassInfo = array();
			$UrlClassInfo = $_POST['UrlClass'];
			$parentid_arr = $_POST['parentid'];
			$parent_id = 0;
			while(true){
				$tmp_parent_id = array_pop($parentid_arr);
				if($tmp_parent_id > 0 ){
					$parent_id = $tmp_parent_id;
					break;
				} 
			}
			//$UrlClassInfo['parentid'] = $parent_id;
			$model->attributes=$_POST['UrlClass'];
			$model-> parentid = $parent_id;
			if($model->save()){
				//$model->updateClassPath();
				showmsg('更新成功！',Yii::app()->createUrl('UrlClass/index'));
				//$this->redirect(array('view','id'=>$model->classid));
			}
		}
		$parentClassArr = $model->getClassNames($model->parentid,1);
		$parentClassHtml = '';
		$classArr = array();
		if(count($parentClassArr)){
			$tmp_parent_id=0;
			foreach ($parentClassArr as $key=>$value){
				$classArr = $m->getSubClass($tmp_parent_id);
				if(count($classArr) > 0){				
					$classArr = array(0=>'全部')+$classArr;
					$parentClassHtml .= CHtml::dropDownList('parentid[]', $key, $classArr,array('id'=>'parentid_'.$tmp_parent_id,'onchange'=>'selectClass(this)'));
				}
				$tmp_parent_id = $key;
			}
			$classArr = $m->getSubClass($tmp_parent_id);
			if(count($classArr) > 0){	
				$classArr = array(0=>'全部')+$classArr;
				$parentClassHtml .= CHtml::dropDownList('parentid[]', 0, $classArr ,array('id'=>'parentid_'.$tmp_parent_id,'onchange'=>'selectClass(this)'));
			}		
		} else {
			$classArr = $m->getSubClass(0);
			$classArr = array(0=>'全部')+$classArr;
			$parentClassHtml .= CHtml::dropDownList('parentid[]',0, $classArr,array('id'=>'parentid_0','onchange'=>'selectClass(this)'));
		}
		
		//获取根分类
//		$root_class = $model->getSubClass();
//		$class_path = explode('/', $model->path);
//		array_pop($class_path);
//		$class_path_ids =implode(',', $class_path);
//		$class_path_names_string = $model->getClassNames($class_path);
		$this->render('update',array(
			'model'=>$model,
			'parentClassHtml'=>$parentClassHtml
			//'root_class'=>$root_class,
			//'class_path'=>$class_path_ids,
			//'class_path_names_string' =>$class_path_names_string,
		));
	}
	
	public function actionMultipleUpdate()
	{
		if(Yii::app()->request->isPostRequest)
		{
			$action = $_POST['action'];
			if($action == 'del'){
				$rmids = $_POST['rmid'];
				foreach ($rmids as $classid=>$value)
				{
					$this->loadModel($id)->delete();
				}
				showmsg('操作成功！', isset($_POST['returnUrl']) ? $_POST['returnUrl'] : yii::app()->createUrl('UrlClass/index'));
			}
			
		}else {
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
		
		
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete()
	{
		$id = $_GET['id'];
		$this->loadModel($id)->delete();
		$this->redirect(Yii::app()->request->urlReferrer);
		
//		if(Yii::app()->request->isPostRequest)
//		{
//			// we only allow deletion via POST request
//			$this->loadModel($id)->delete();
//
//			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
//			if(!isset($_GET['ajax']))
//				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
//		}
//		else
//			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$this->layout = 'main';
		
		$classid = Yii::app()->request->getParam('classid');
		$className = Yii::app()->request->getParam('class_name');
		$condition = '';
		if($classid !=''){
			$condition .= 'classid='.$classid;
		}
		if($className){
			if($condition !=''){
				$condition .= ' AND classname like "%'.$className.'%"';
			} else {
				$condition .= 'classname like "%'.$className.'%"';
			}
		}
		$criteria=new CDbCriteria(array(
			'condition'=>$condition,
			'order'=>'parentid ASC,displayorder DESC',
		));
		
		$dataProvider=new CActiveDataProvider('UrlClass',
													array(
														'pagination'=>array(
															'pageSize'=>Yii::app()->params['postsPerPage'],
														),
														'criteria'=>$criteria,
													)
											 );
											 
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));		
	}
	
	
	/**
	 * 异步请求分类列表
	 */
	public function actionAjaxGetList()
	{
		$m = new UrlClass();
		$parentid = intval($_GET['parentid']); 
		$parentClassArr = $m->getClassNames($parentid,1);
		$parentClassHtml = '';
		$classArr = array();
		if(count($parentClassArr)){
			$tmp_parent_id=0;
			foreach ($parentClassArr as $key=>$value){
				$classArr = $m->getSubClass($tmp_parent_id);
				if(count($classArr) > 0){
					$classArr = array(0=>'全部')+$classArr;
					$parentClassHtml .= CHtml::dropDownList('parentid[]', $key, $classArr,array('id'=>'parentid_'.$tmp_parent_id,'onchange'=>'selectClass(this)'));
				}
				$tmp_parent_id = $key;
			}
			$classArr = $m->getSubClass($tmp_parent_id);
			if(count($classArr) > 0){
				$classArr = array(0=>'全部')+$classArr;
				$parentClassHtml .= CHtml::dropDownList('parentid[]', 0, $classArr ,array('id'=>'parentid_'.$tmp_parent_id,'onchange'=>'selectClass(this)'));
			}
			
		} else {
			$classArr = $m->getSubClass(0);
			if(count($classArr) > 0){
				$classArr = array(0=>'全部')+$classArr;
				$parentClassHtml .= CHtml::dropDownList('parentid[]',0, $classArr,array('id'=>'parentid_0','onchange'=>'selectClass(this)'));
			}
		}
		echo $parentClassHtml;
		
//		if(isset($_GET['parentid'])){ //GET 参数
//			$parentid = intval($_GET['parentid']);
//		} else {
//			$parentid = 0;
//		}
//		$class_list = UrlClass::model()->getSubClass($parentid);
//		if($class_list){
//			echo CJSON::encode($class_list);
//		} else {
//			echo 'false';
//		}
	}
	/**
	 * 查询分类
	 */
	public function actionSearch()
	{
		try
        {
					    
            if( isset($_GET['k']) )
            {
                header("Content-type: text/html; charset=utf-8");
                echo json_encode(UrlClass::model()->search_class($_GET['k']));
            }
            exit;
        }
        catch( Exception $e )
        {
            
        }
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new UrlClass('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['UrlClass']))
			$model->attributes=$_GET['UrlClass'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=UrlClass::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='url-class-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
